# -*- ecoding: utf-8 -*-
# @ModuleName: conftest
# @Author: wangwei 
# @Time: 2023/10/18 10:49
from typing import List

import pytest

from api.buyer.buyerbaseapi import BuyerBaseApi
from api.buyer.login import Login
from api.manager.manager_login import ManagerLogin
from api.manager.managerbaseapi import ManagerBaseApi
from api.seller.sellerbaseapi import SellerBaseApi
from api.seller.sellerlogin import SellerLogin
from common.file_load import read_yaml
from common.logger import GetLogger
from common.mysql_db import MysqlUtil
from common.redis_util import RedisUtil


def pytest_collection_modifyitems(
        session: "Session", config: "Config", items: List["Item"]
) -> None:
    for item in items:
        item.name = item.name.encode("utf-8").decode("unicode-escape")
        item._nodeid = item._nodeid.encode("utf-8").decode("unicode-escape")


@pytest.fixture(scope='session', autouse=True)
def aaaset_loger():
    GetLogger.logger = GetLogger.get_logger()
    GetLogger.logger.info("开始了")


@pytest.fixture(scope='session', autouse=True)
def set_buyer_token():
    username = read_yaml("/config/common.yml").get('buyerName')[0]
    password = read_yaml("/config/common.yml").get('buyerPassword')[0]
    resp = Login(username=username, password=password).send()
    BuyerBaseApi.buyer_token = resp.json().get("access_token")
    BuyerBaseApi.uid = resp.json().get('uid')


@pytest.fixture(scope='session', autouse=True)
def set_seller_token():
    username = read_yaml("/config/common.yml").get('sellerName')
    password = read_yaml("/config/common.yml").get('sellerPassword')
    resp = SellerLogin(username=username, password=password).send()
    SellerBaseApi.seller_token = resp.json().get("access_token")


@pytest.fixture(scope='session', autouse=True)
def set_manager_token():
    username = read_yaml("/config/common.yml").get('managerName')
    password = read_yaml("/config/common.yml").get('managerPassword')
    resp = ManagerLogin(username=username, password=password).send()
    ManagerBaseApi.manager_token = resp.json().get("access_token")


@pytest.fixture(scope='session', autouse=True)
def get_redis():
    yaml_data = read_yaml("/config/redis.yml").get('mtxshop')
    host = yaml_data.get('host')
    password = yaml_data.get('password')
    port = yaml_data.get('port')
    redis = RedisUtil(host=host, password=password, port=port)
    yield redis
    redis.close()


@pytest.fixture(scope='session', autouse=True)
def get_mysql():
    yaml_data = read_yaml("/config/db.yml").get('mtxshop')
    print(yaml_data)
    host = yaml_data.get('host')
    password = yaml_data.get('password')
    port = yaml_data.get('port')
    username = yaml_data.get('username')
    GetLogger().logger.info(f"数据库信息：host:{host}-password:{password}-port:{port}-user:{username}")
    mysql = MysqlUtil(host=host, user=username, port=port, password=password)
    yield mysql
    mysql.close()
